import { Divider } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import ZcoForm from '../ZcoForm';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
import styled from '@emotion/styled';

interface FormPreviewProps {
	list: {
		id: number | string;
		title: string;
		detailId?: string;
	}[];
}

const FormPrviewContainer = styled.div`
	padding: 10px 0;
`;

const FormPreview = (props: FormPreviewProps) => {
	const { list = [] } = props;

	const [form, setForm] = useState<{ id: string | number; title: string; detailId?: string }>({ id: '', title: '', detailId: undefined });
	const [page, setPage] = useState<number>(1);

	useEffect(() => {
		if (list.length > 0) {
			if (!list[page - 1]) {
				setPage(1);
				setForm(list[0]);
			} else {
				setForm(list[page - 1]);
			}
		}
	}, [list]);

	const changePage = (curPage: number, size: number) => {
		setPage(curPage);
		setForm(list[curPage - 1]);
	};

	const PaginationView = useMemo(() => {
		if (list.length === 0) return <></>;
		return (
			<>
				<Divider></Divider>
				<ZcoForm id={form.id} detailId={form.detailId} title={form.title} height={400} />
				<Pagination pageSize={1} current={page} defaultCurrent={page} onChange={changePage} total={list.length} style={{ textAlign: 'right', margin: '10px 0' }} />
			</>
		);
	}, [list, form, page]);

	return <FormPrviewContainer>{PaginationView}</FormPrviewContainer>;
};

export default FormPreview;
